import csv
from datetime import datetime
import copy

class Log():
    def __init__(self, time, money, holdings, value, operated):
        self.time = time #交易时间
        self.money = money #剩余流动资金
        self.holdings = holdings #字典：{ id:股票数量 }，当前持有的股票
        self.value = value # 当前总价值,即所有股票卖出去加上流动资金的总和
        self.operated = operated # 这一轮实际上做的操作，是一个列表，元素是utils.py 定义的 Operation


class Logs():
    def __init__(self, logname, strategyname):
        if logname is None:
            logname = ''
        if strategyname is None:
            strategyname = ''
        self.logname = logname + strategyname + datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        self.logs = []

    def record(self, log):
        self.logs.append(copy.deepcopy(log))

    def print(self):
        for log in self.logs:
            print(log.time, log.value, log.money, log.holdings, log.operated)

    def output(self, set_name = None):
        if set_name is not None:
            fname = set_name
        else:
            fname = self.logname
        with open("./Logs/"+ fname +'.tsv', 'w', newline='', encoding='utf-8') as outf:
            writer = csv.writer(outf, delimiter = '\t')
            for log in self.logs:
                writer.writerow([log.time, round(log.value, 2), round(log.money, 2), log.holdings, [[op.op, op.id, op.value, op.ratio] for op in log.operated]])
        print("log saved as:", "./Logs/"+ fname + '.csv')










